<!--
  功能：平台应用管理
  作者：menghao.yan
  邮箱：yxs2615@163.com
  时间：2022年10月20日 23:48:24
-->
<template>
  <div>
    <div class="search">
      <a-space>
        <a-input v-model:value="search.appName" placeholder="应用名称检索" />
        <a-input v-model:value="search.appCode" placeholder="应用编码检索" />
        <a-input v-model:value="search.keyName" placeholder="Key名称检索" />
        <a-input v-model:value="search.keyCode" placeholder="Key编码检索" />
        <a-button type="primary" @click="serch">
          <template #icon>
            <search-outlined />
          </template>
          检索
        </a-button>
        <a-button type="primary" @click="insert">
          <template #icon>
            <plus-outlined />
          </template>
          创建应用
        </a-button>
      </a-space>
    </div>
    <a-empty v-if="!tableData || tableData.length == 0" />
    <a-collapse expandIconPosition="right" v-for="app in tableData" class="content">
      <a-collapse-panel>
        <template #header>
          <div class="header">
            <div>
              <div class="title">{{app?.name}} - <span class="msg">{{app?.message}}</span></div>
              <div class="update-time">更新 - {{app?.updateTime}}</div>
            </div>
            <div>
              <edit-outlined class="icon" @click.stop="updateRow(app)" />
              <delete-outlined class="icon" @click.stop="delRow(app)" />
              <plus-circle-outlined class="icon" @click.stop="insertKey(app?.code)" />
            </div>
          </div>
        </template>

        <a-table :data-source="app?.keyList" bordered :pagination="false" size="small">
          <a-table-column key="name" data-index="name" title="Key名称" width="15%" />
          <a-table-column key="code" data-index="code" title="Key" width="25%">
            <template #default="{ text: code }">
              <a-space>
                <span style="color:#1890ff">{{code}}</span>
                <a-button type="link" @click="copyStr(code)">
                    <template #icon><copy-filled /></template>
                </a-button>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column key="time" title="Key有效期" width="20%">
            <template #default="{ record }">
              {{record?.startTime}} - {{record?.endTime}}
            </template>
          </a-table-column>
          <a-table-column key="time" title="调用上限" width="20%">
            <template #default="{ record }">
              <a-space direction="vertical">
                <div>
                  <span style="color:#1890ff">上限: </span>
                  <a-tag color="processing">{{formCurrency(record?.sumCount).format()}} 次</a-tag>
                </div>
                <div v-if="record?.callCount== record?.sumCount">
                  <span style="color:#000000">剩余: </span>
                  <a-tag color="default">{{formCurrency(record?.sumCount).subtract(record?.callCount).format()}} 次</a-tag><span style="color:#000000">已用尽</span>
                </div>
                <div v-else-if="record?.callCount>0 && formCurrency(record?.callCount).divide(record?.sumCount).multiply(100) > 90">
                  <span style="color:red">剩余: </span>
                  <a-tag color="error">{{formCurrency(record?.sumCount).subtract(record?.callCount).format()}} 次</a-tag><span style="color:red">即将用尽</span>
                </div>
                <div v-else>
                  <span style="color:green">剩余: </span>
                  <a-tag color="green">{{formCurrency(record?.sumCount).subtract(record?.callCount).format()}} 次</a-tag>
                </div>
              </a-space>
            </template>
          </a-table-column>
          <a-table-column key="action" title="操作" width="20%">
            <template #default="{ record }">
              <a-badge-ribbon color="volcano" text="Key失效" v-if="record.isValid=='N'">
                <a-button type="link" @click="updateRowKey(record, app?.code)">设置</a-button>
                <a-button type="link" @click="updateValidRowKey(record.id, 'Y')">令其有效</a-button>
                <a-button type="link" danger="" @click="delRowKey(record)">删除</a-button>
              </a-badge-ribbon>
              <template v-if="record.isValid=='Y'">
                <a-button type="link" @click="updateRowKey(record, app?.code)">设置</a-button>
                <a-button type="link" danger="" @click="updateValidRowKey(record.id, 'N')">令其失效</a-button>
                <a-button type="link" danger="" @click="delRowKey(record)">删除</a-button>
              </template>
            </template>

          </a-table-column>
        </a-table>
      </a-collapse-panel>
    </a-collapse>

    <a-pagination v-model:current="pagination.current" :total="pagination.total" v-model:pageSize="pagination.pageSize" :showSizeChanger="pagination.showSizeChanger" :showTotal="pagination.showTotal" @change="pagination.onChange" hideOnSinglePage style="float:right" />

    <a-modal :open="form.visible" :title="form.type=='insert'?'创建应用信息':'编辑应用信息' " @change="form.visible = false" :footer="null" destroyOnClose>
      <formModel :row="form.row" :type="form.type" @success="successForm" />
    </a-modal>

    <a-modal :open="formKey.visible" :title="formKey.type=='insert'?'创建key信息':'编辑key信息' " @change="formKey.visible = false" :footer="null" destroyOnClose>
      <formKeyModel :row="formKey.row" :appCode="formKey.appCode" :type="formKey.type" @success="successFormKey" />
    </a-modal>
  </div>
</template>

<script>
import {
  PlusOutlined,
  AlertFilled,
  EditOutlined,
  DeleteOutlined,
  PlusCircleOutlined,
  SearchOutlined,
  CopyFilled
} from "@ant-design/icons-vue";
import currency from "currency.js";
import useClipboard from "vue-clipboard3";
import { pageList, remove } from "@/api/platform/plAppApi";
import plAppKeyApi from "@/api/platform/plAppKeyApi";
import { defineComponent, reactive, toRefs, onMounted } from "vue";
import formModel from "./formModel.vue";
import formKeyModel from "./formKeyModel.vue";
import { message } from "ant-design-vue";
import {} from "vue-router";
import {useStore} from "vuex";

export default defineComponent({
  name: "",
  props: {},
  emits: [],
  setup(props, context) {
     const store = useStore();
    const { toClipboard } = useClipboard();

    const search = {
      appName: "",
      appCode: "",
      keyName: "",
      keyCode: "",
      userCode: store.state.user.userInfo.code || ""
    };

    const pagination = {
      current: 1,
      pageSize: 10,
      showSizeChanger: true,
      total: 0,
      showTotal: (total, range) => {
        return `${range[0]}-${range[1]} 共 ${total} 条数据`;
      },
      onChange: (page, pageSize) => {
        data.pagination.current = page;
        data.pagination.pageSize = pageSize;
        initPageList();
      }
    };
    const data = reactive({
      search,
      pagination,
      tableData: null,
      form: {
        row: null,
        type: "insert",
        visible: false
      },
      formKey: {
        appCode: null,
        row: null,
        type: "insert",
        visible: false
      }
    }); //里面写所有的响应式数据，像vue2中的data一样

    /* 创建数据 */
    let insert = () => {
      data.form.visible = true;
      data.form.type = "insert";
    };

    /* 更新行数据 */
    let updateRow = row => {
      data.form.row = row;
      data.form.visible = true;
      data.form.type = "update";
    };

    // 表单成功回调函数
    let successForm = () => {
      initPageList();
      data.form.visible = false;
    };
    /*删除行数据, 并且删除所有的key:todo */
    let delRow = row => {
      let params = [row.id];
      remove(params).then(resd => {
        message.success(`${resd} 条数据已删除`);
        initPageList();
      });
    };

    /*添加应用的key */
    let insertKey = appCode => {
      data.formKey.appCode = appCode;
      data.formKey.visible = true;
      data.formKey.type = "insert";
    };

    /* 更新key行数据 */
    let updateRowKey = (row, appCode) => {
      data.formKey.appCode = appCode;
      data.formKey.row = row;
      data.formKey.visible = true;
      data.formKey.type = "update";
    };

    /*删除key 行数据, 并且删除所有的key:todo */
    let delRowKey = row => {
      let params = [row.id];
      plAppKeyApi.remove(params).then(resd => {
        message.success(`${resd} 条数据已删除`);
        initPageList();
      });
    };

    /**设置key的有效状态 */
    let updateValidRowKey = (keyId, valid) => {
      let params = {
        id: keyId,
        isValid: valid
      };
      plAppKeyApi.updateValid(params).then(resd => {
        message.success(`设置成功`);
        initPageList();
      });
    };

    // 表单成功回调函数
    let successFormKey = () => {
      initPageList();
      data.formKey.visible = false;
    };

    /**拷贝信息 */
    let copyStr = str => {
      toClipboard(str);
      message.success(`拷贝成功`);
    };

    // 计算数值
    let formCurrency = value => currency(value, { precision: 0, symbol: "" });

    // 检索
    let serch = () => {
      pagination.current = 1;
      initPageList();
    };

    // 初始化表格列表
    let initPageList = () => {
      let params = {
        current: pagination.current,
        size: pagination.pageSize,
        appName: search.appName,
        appCode: search.appCode,
        keyName: search.keyName,
        keyCode: search.keyCode,
        userCode: search.userCode
      };
      pageList(params).then(resd => {
        data.tableData = resd.records;
        data.pagination.total = resd.total;
      });
    };

    // 页面初始化
    onMounted(() => {
      initPageList(); // 初始化表格
    });

    return {
      ...toRefs(data),
      insert,
      updateRow,
      successForm,
      successFormKey,
      delRow,
      delRowKey,
      insertKey,
      updateRowKey,
      updateValidRowKey,
      serch,
      formCurrency,
      currency,
      copyStr
    };
  },
  components: {
    formModel,
    formKeyModel,
    PlusOutlined,
    AlertFilled,
    EditOutlined,
    DeleteOutlined,
    PlusCircleOutlined,
    SearchOutlined,
    CopyFilled
  }
});
</script>

<style scoped lang="scss">
.crud,
.search {
  margin-bottom: 10px;
}
.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .title {
    margin-top: 12px;
    margin-bottom: 10px;
    font-size: 1rem;
    font-weight: 600;
    color: #2b2b33;
    width: 100%;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
  .msg,
  .update-time {
    font-size: 0.8rem;
    color: #6b6b77;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .icon {
    font-size: 1rem;
    font-weight: bold;
    color: #1890ff;
    margin-right: 16px;
  }
}

.content {
  margin-bottom: 10px;
}
</style>